﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 修改采购/委外订单信息
    /// </summary>
    public class UpdatePurchaseHandler : IRequestHandler<UpdatePurchaseCommand, Result>
    {
        /// <summary>
        /// 采购/委外订单仓储
        /// </summary>
        private readonly IBaseRepository<PurchaseOutsources> _purchaseOutsourceRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UpdatePurchaseHandler> _logger;

        /// <summary>
        /// Mapper类
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="purchaseOutsourceRepository"></param>
        /// <param name="logger"></param>
        /// <param name="mapper"></param>
        public UpdatePurchaseHandler(IBaseRepository<PurchaseOutsources> purchaseOutsourceRepository,
            ILogger<UpdatePurchaseHandler> logger,
            IMapper mapper)
        {
            _purchaseOutsourceRepository = purchaseOutsourceRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 修改采购/委外订单信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(UpdatePurchaseCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //查询编码与名称是否存在
                var model = await (await _purchaseOutsourceRepository.GetAll()).Where(x => x.PurchaseId == request.PurchaseId && x.PurchaseNumber == request.PurchaseNumber && x.PurchaseName == request.PurchaseName).CountAsync();
                //判断如果存在提醒
                if (model > 0)
                {
                    result.Msg = "编码或名称已存在,请重新输入";
                }
                else
                {
                    //Mapper转换
                    var purchase = _mapper.Map<PurchaseOutsources>(request);
                    var res = await _purchaseOutsourceRepository.Update(purchase);
                    if (res > 0)
                    {
                        result.Code = (int)CommonErrorCode.Success;
                        result.Msg = "修改采购/委外订单信息成功";
                    }
                }
                 
            }
            catch (Exception ex)
            {
                result.Msg = "修改采购/委外订单信息异常" + ex.Message;
                _logger.LogError("修改采购/委外订单信息异常" + ex.Message);
            }
            return result;
        }
    }
}
